package cn.rongdao.jrkabao.ui.main.mainfragment.personal;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.View;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRCollection;
import com.mifengkong.frtools.util.FRLog;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.PictureUtil;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import cn.rongdao.jrkabao.BuildConfig;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.bean.main.personal.PersonInfoBean;
import cn.rongdao.jrkabao.model.main.personal.PersonInfoModel;
import cn.rongdao.jrkabao.model.takephoto.UploadAvatarModel;
import cn.rongdao.jrkabao.util.MyGlideEngine;
import cn.rongdao.jrkabao.util.permission.GoToPermissionSetting;

/**
 * Created by jack on 2017/12/29
 */

public class PersonInfoActivity extends BaseAutoFinishActivity {

    private boolean isHavePermission;
    private static final int REQUEST_CODE_CHOOSE = 0x010;

    public static void start(Context context) {
        FRStartActivity.start(context, PersonInfoActivity.class);
    }

    @BindView(R.id.api_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.api_head_portrait)
    PersonInfoUIComponent headPortrait;
    @BindView(R.id.api_phone)
    PersonInfoUIComponent phone;
    @BindView(R.id.api_name)
    PersonInfoUIComponent name;
    @BindView(R.id.api_id_card)
    PersonInfoUIComponent idCard;

    private String imageSuffix;

    @Override
    protected int layoutRes() {
        return R.layout.activity_person_info;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitleBar();

        initData();
        initListener();
        checkPermission();
    }

    private void checkPermission() {
        AndPermission.with(this)
                .requestCode(100)
                .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        isHavePermission = true;
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        isHavePermission = false;
                    }
                }).start();
    }

    /**
     * 是否缺少权限
     */
    protected boolean lackPermission() {
        if (!isHavePermission) {
            GoToPermissionSetting.showSnackBar(getActivity(), findViewById(android.R.id.content));
            return true;
        }
        return false;
    }

    private void initListener() {
        headPortrait.setOnItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!lackPermission()) {
                    Matisse.from(thisActivity())
                            .choose(MimeType.allOf()) // 1、获取 SelectionCreator
                            .countable(true)
                            .maxSelectable(1)
                            .capture(true)
                            .captureStrategy(new CaptureStrategy(true, FRCollection.appendAsString(BuildConfig.APPLICATION_ID, ".fileprovider", "")))
                                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f)
                                    .theme(R.style.MyPhotoSelector)
                                    .imageEngine(new MyGlideEngine()) // 2、配置各种各样的参数
                                    .forResult(REQUEST_CODE_CHOOSE); // 3、打开 MatisseActivity
                }
            }
        });
    }

    private void initData() {
        headPortrait.setName("头像");
        phone.setName("手机号");
        name.setName("姓名");
        idCard.setName("身份证");
        phone.setViewLineVisible(false);
        idCard.setViewLineVisible(false);
        PersonInfoModel.getInstance().execute(new FRBaseObserver<PersonInfoBean>(this, "加载中，请稍候...") {
            @Override
            protected void onBaseNext(PersonInfoBean data) {
                headPortrait.setIvAvatar(data.getUser_logo());
                phone.setContent(data.getPhone());
                if (!FRString.isEmpty(data.getId_card())) {
                    idCard.setContent(data.getId_card());
                }
                if (!FRString.isEmpty(data.getName())) {
                    name.setContent(data.getName());
                }
            }
        });
    }

    private void initTitleBar() {
        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary));
        titleBarUIComponent.initTitle("个人信息");
        titleBarUIComponent.initLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GoToPermissionSetting.REQUEST_CODE_PERMISSION_SETTING) {
            checkPermission();
        } else if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> imageList = Matisse.obtainResult(data);
            FRLog.error("mSelected: " + Matisse.obtainResult(data));
            if (null != imageList && imageList.size() > 0) {
                String imagePath = FRString.valueOf(imageList.get(0));
                if (!PictureUtil.judgePictureType(imagePath)) {
                    imagePath = PictureUtil.getRealFilePath(thisActivity(), imageList.get(0));
                }
                FRLog.error("imagePath: " + imagePath);
                imageSuffix = imagePath.substring(imagePath.lastIndexOf("."));
                FRLog.error("imageSuffix: " + imageSuffix);
                uploadAvatar(PictureUtil.getBase64DataFromBitmap(imageList.get(0)));
            }
        }
    }


    private void uploadAvatar(String base64Data) {
        UploadAvatarModel.getInstance().execute(base64Data, imageSuffix, new FRBaseObserver<String>(this, "上传中，请稍候...") {
            @Override
            protected void onBaseNext(String data) {
                EventBus.getDefault().post(new UploadAvatarSuccessEvent());
                headPortrait.setIvAvatar(data);
            }
        });
    }
}
